home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: Wed, 03 Apr 96 16:17:45 GMT
- Organization: none
- Message-ID: <828548265snz@genesis.demon.co.uk>
- References: <31624BC2.70D2@sooner.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <31624BC2.70D2@sooner.net> edwbush@sooner.net "Eddie Bush" writes:
-
- >I am trying to construct a C function that will recursively convert
- >a string such as "1234" into it's integer equivelant (1234).
- >
- >Here is what I know:
- >1)if you subtract the character "0" from any of the other digits "1".."9"
- > you will get the integer value of that characer.
- > Example: "1" - "0" is equal to 1
-
- Not true "1" and "0" are strings (i.e. have type array of char) and -
- cannot be applied to 2 of these. However '1' - '0' is equal to 1.
-
-
- > "2" - "0" is equal to 2
- > .
- > .
- > .
- > "9" - "0" is equal to 9
-
- Similarly.
-
- >2)the function should be called with a character pointer:
- > Such as: convert("1234");
- > making the prototype look something like:
- > int convert(char *p);
-
- Or consider
-
- int convert(const char *p);
-
- since you aren't going to modify the source string (certainly not if it
- could be a string literal).
-
- >Does anyone have an idea? This is sorta stumping me. I am aware of
- >atoi, but I am wanting to write a recursive function that does that --
- >for the fun of it. It's sort of a little puzzle to help me learn
- >recursion. Any ideas?
-
- I think you've picked a bad example. You really need an extra argument in
- this case to pass on a running accumulator. A more suitable problem would
- be to write a recursive function that is passed an integer (unsigned is
- easiest) and writes the character representation to stdout.
-
- Define a recursive algorithm i.e. one defined in terms of a simpler form
- of the problem, with a termination condition (i.e. hitting the end of the
- input string in this case). Consider
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-